package fr.cephb.operon.common;

import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import fr.cephb.joperon.core.Operon;

/** base class for all command application */
public class CmdLineApplication
	{
	/** BDB home */
	private File db_home = new File(Operon.guessBerkeleyDBHome());
	/** logger for this application */
	private Logger logger;
	/** stdout */
	private PrintStream _stdout=null;
	/** stdout */
	private PrintWriter _writer=null;
	
	protected CmdLineApplication()
		{
		this.logger = Logger.getAnonymousLogger();
		this.logger.setLevel(Level.OFF);
		}
	
	public Logger log()
		{
		return this.logger;
		}
	
	/** set stdout as stream */
	public void setOutputStream(PrintStream out)
		{
		if(_stdout!=null)
			{
			throw new IllegalArgumentException("output was already set");
			}
		_stdout=out;
		}
	
	
	/** get stdout as stream */
	public PrintStream getOutputStream()
		{
		if(_stdout==null)
			{
			_stdout=System.out;
			}
		return _stdout;
		}
	
	/** get stdout as writer */
	public PrintWriter getWriter()
		{
		if(_writer==null)
			{
			_writer= new PrintWriter(getOutputStream());
			}
		return _writer;
		}
	
	
	/** return the BerkeleyDB environement directory */
	protected File getBerkeleyDBHome() {
		return db_home;
		}
	
	/** print the usage for this application */
	protected void usage(PrintStream out)
		{
		out.print("-h HELP this screen");
		out.print("--db-home BerkeleyDB environement dir (OPTIONAL) Default: "+getBerkeleyDBHome());
		out.print("--log-level <LEVEL> any of ( SEVERE WARNING INFO CONFIG FINE FINER FINEST OFF) Default: OFF");
		}
	
	/** parses the options on the command line
	 * 
	 * @param args command line arguments
	 * @param optind  the current index in the command line arguments
	 * @return -1 if the option is not handled by this tool or the new index just before in the options
	 */
	protected int parseOption(String args[],int optind)
		{
		if( args[optind].equalsIgnoreCase("-h") ||
			args[optind].equalsIgnoreCase("--h")||
			args[optind].equalsIgnoreCase("--help"))
				{
				usage(System.out);
				System.exit(0);
				}
		//parses Berkeley HOME
		else if( args[optind].equals("--db-home"))
			{
			this.db_home= new File(args[++optind]);
			}
		//parses logging Level
		else if( args[optind].equals("--log-level"))
			{
			this.logger.setLevel(Level.parse(args[++optind].toUpperCase()));
			}
		else
			{	
			return -1;
			}
		return optind;
		}
	}
